package com.bingqing.common;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.bingqing.entity.Admin;
import com.bingqing.entity.Log;
import com.bingqing.service.LogService;
import com.bingqing.utils.JwtTokenUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * ClassName: LogAspect
 * Package: com.bingqing.common
 * Description:
 *
 * @Author liuyujie
 * @Create 2024-03-12 19:47
 * @Version 1.0
 */
@Component
@Aspect
public class LogAspect {
    @Resource
    private LogService logService;

    @Around("@annotation(autoLog)")
    public Object doAround(ProceedingJoinPoint joinPoint, AutoLog autoLog) throws Throwable {
        //1.操作内容
        String name = autoLog.value();
        //2.操作时间
        String time = DateUtil.now();
        //3.操作人
        String username = "";
        Admin user = JwtTokenUtils.getCurrentUser();
        if(ObjectUtil.isNotNull(user)){
            username = user.getName();
        }
        //4.操作人IP
        HttpServletRequest request =((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String ip = request.getRemoteHost();
        //5.执行具体的接口
        Result result = (Result)joinPoint.proceed();

        Object data = result.getData();
        //如果是登录接口，返回的是登录用户
        if(data instanceof Admin){
            Admin admin = (Admin) data;
            username = admin.getName();
        }
        //6.再往日志表中写入一条日志记录
        Log log = new Log(null,name,time,username,ip);
        logService.add(log);
        //7.你可以走了，去返回前台报到吧
        return result;
    }
}
